import { defineStore } from 'pinia';
import {ref} from 'vue'
import {requestPermission, type Permission, type Menum} from '@/api/auth'
import {useRouter, useRoute} from 'vue-router'
import {requiredRoutes, menumRoutes} from '@/router/routes'

const router = useRouter()

export const useRouterStore = defineStore('routerStore', () => {
  const menumRef = ref<Menum[] | null | undefined>(null);
  const isRouteLoad = ref<boolean>(false)

  // const isLoggedIn = computed(() => sessionIdRef.value !== null);

  async function requestPermissionAction() {
    const permission = await requestPermission();
    console.log('permission',permission)
    menumRef.value = permission.menums;
    return permission.menums
  }

  function filterRoutesRecursively(menums?: Menum[]) {
    menums?.forEach(menum => {
      menumRoutes.forEach(route => {
        if(route.meta?.filteredKey === menum.matchedKey) {
          router.addRoute('Layout', route)
        }
      })

      if(menum.children) {
        filterRoutesRecursively(menum.children)
      }
    })
  }

  async function filterRoutes() {
    const menums = await requestPermissionAction()
    filterRoutesRecursively(menums)
    isRouteLoad.value = true
  }

  return {menumRef, isRouteLoad, filterRoutes};
});
